/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package co.yixiang.controller.manager.adopt;

import cn.hutool.core.util.StrUtil;
import co.yixiang.common.annotation.Log;
import co.yixiang.common.annotation.NoRepeatSubmit;
import co.yixiang.common.constant.ShopConstants;
import co.yixiang.common.exception.BadRequestException;
import co.yixiang.modules.adopt.entity.domain.YxAdoptProduct;
import co.yixiang.modules.adopt.entity.domain.YxAdoptVariety;
import co.yixiang.modules.adopt.entity.dto.YxAdoptVarietyQueryCriteria;
import co.yixiang.modules.adopt.service.YxAdoptProductService;
import co.yixiang.modules.adopt.service.YxAdoptVarietyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hupeng
 * @date 2019-10-03
 */
@Api(tags = "认养:品种管理")
@RestController
@RequestMapping("api/yxAdoptVariety")
public class AdoptVarietyController {

    @Autowired
    private YxAdoptVarietyService yxAdoptVarietyService;
    @Autowired
    private YxAdoptProductService yxAdoptProductService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('admin','common','common','cate:list')")
    public void download(HttpServletResponse response, YxAdoptVarietyQueryCriteria criteria) throws IOException {
        yxAdoptVarietyService.download(yxAdoptVarietyService.queryAll(criteria), response);
    }


    @Log("分页查询品种")
    @ApiOperation(value = "分页查询品种")
    @GetMapping
    @PreAuthorize("hasAnyRole('admin','common','common','YXADOPTVARIETY_ALL','YXADOPTVARIETY_SELECT')")
    public ResponseEntity getYxAdoptVariety(YxAdoptVarietyQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity( yxAdoptVarietyService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("分页查询品种")
    @ApiOperation(value = "分页查询品种")
    @GetMapping(value = "/cate/{cateId}")
    @PreAuthorize("hasAnyRole('admin','common','common','YXADOPTVARIETY_ALL','YXADOPTVARIETY_SELECT')")
    public ResponseEntity getYxAdoptVarietyByCateId(@PathVariable Integer cateId) {
        return new ResponseEntity( yxAdoptVarietyService.selectListByCateId(cateId), HttpStatus.OK);
    }

    @Log("新增品种分类")
    @ApiOperation(value = "新增品种分类")
    @PostMapping
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PreAuthorize("hasAnyRole('admin','common','common','YXADOPTVARIETY_ALL','YXADOPTVARIETY_CREATE')")
    public ResponseEntity create(@Validated @RequestBody YxAdoptVariety resources) {
        if (StrUtil.isBlank(resources.getPic())) {
            throw new BadRequestException("子分类图片必传");
        }
        if (StrUtil.isBlank(resources.getName())) {
            throw new BadRequestException("品种名称不能为空");
        }
//        boolean checkResult = yxAdoptVarietyService.checkVarietyExist(resources.getName(), resources.getId());
//        if (!checkResult) {
//            throw new BadRequestException("品种名称已经存在!");
//        }
        return new ResponseEntity(yxAdoptVarietyService.save(resources), HttpStatus.CREATED);
    }

    @NoRepeatSubmit
    @Log("修改品种分类")
    @ApiOperation(value = "修改品种分类")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PutMapping
    @PreAuthorize("hasAnyRole('admin','common','common','YXADOPTVARIETY_ALL','YXADOPTVARIETY_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxAdoptVariety resources) {
        if (StrUtil.isBlank(resources.getPic())) {
            throw new BadRequestException("品种图片必传");
        }
        if (StrUtil.isBlank(resources.getName())) {
            throw new BadRequestException("品种名称不能为空");
        }
        boolean checkResult = yxAdoptVarietyService.checkVarietyExist(resources.getName(), resources.getId());
        if (!checkResult) {
            throw new BadRequestException("品种名称已经存在!");
        }
        yxAdoptVarietyService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除品种分类")
    @ApiOperation(value = "删除品种分类")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @DeleteMapping(value = "/{id}")
    @PreAuthorize("hasAnyRole('admin','common','common','YXADOPTVARIETY_ALL','YXADOPTVARIETY_DELETE')")
    public ResponseEntity delete(@PathVariable String id) {
        String[] ids = id.split(",");
        for (String newId : ids) {
            this.delCheck(Integer.valueOf(newId));
            yxAdoptVarietyService.removeById(Integer.valueOf(newId));
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    /**
     * 检测删除分类
     * @param id 分类id
     */
    private void delCheck(Integer id) {
        final YxAdoptVariety varietyCategory = yxAdoptVarietyService.getById(id);
        Long countP = yxAdoptProductService.lambdaQuery()
                .eq(YxAdoptProduct::getVarietyName,varietyCategory.getName())
                .count();
        if (countP > 0) {
            throw new BadRequestException("当前品种下有商品不可删除");
        }
    }
}
